import requests
import os
import datetime
import copy
# AnythingLLM API 基础 URL
BASE_URL = "http://localhost:3001/api/v1"
API_KEY = "Bearer Z27C9VS-AZZMGRE-KY8Z7T8-6XY3TQS"


def getFtime():
    FormatTime = datetime.datetime.now().strftime("%d日%H:%M:%S")
    print(FormatTime)
    return FormatTime


# 新建工作区
def create_workspace(workspace_name):
    """    创建一个新的工作区    """
    url = f"{BASE_URL}/workspace/new"
    headers = {"accept": "application/json",
               "Authorization": API_KEY,
               "Content-Type": "application/json"}
    data = {"name": workspace_name,
            "similarityThreshold": 0.7,
            "openAiTemp": 0.7,
            "openAiHistory": 20,
            "openAiPrompt": "Custom prompt for responses",
            "queryRefusalResponse": "Custom refusal message",
            "chatMode": "query",  # chat
            "topN": 4}
    response = requests.post(url, headers=headers, json=data)
    # print(response.json().get('workspace'))
    # print(response.json().get('workspace').get("id"))

    # 通过判断能否获取到 workspace 的 id，判定 workspace 是否创建成功
    try:
        if response.json().get('workspace').get("id"):
            workspace_create_result = True
    except Exception as e:
        workspace_create_result = False
    if workspace_create_result:
        workspaceSlug = response.json().get("workspace").get("slug")
        print("workspace_slug: ", workspaceSlug)
        print(f"【创建工作区成功】，状态码: {response.status_code}, 响应: {response.text}")
        return workspaceSlug
        # {"message":null, "workspace":
        # {"id":9,"name":"My New Workspace","slug":"my-new-workspace","vectorTag":null,
        # "createdAt":"2025-02-17T13:50:35.201Z","openAiTemp":null,"openAiHistory":20,
        # "lastUpdatedAt":"2025-02-17T13:50:35.201Z","openAiPrompt":null,"similarityThreshold":0.25,
        # "chatProvider":null,"chatModel":null,"topN":4,"chatMode":"chat","pfpFilename":null,
        # "agentProvider":null,"agentModel":null,"queryRefusalResponse":null,"vectorSearchMode":"default"}}
    else:
        print(f"创建工作区失败，状态码: {response.status_code}, 响应: {response.text}")
        return None
        # {"workspace":null,"message":"name cannot be null"}


def upload_file(file_path, workspaceSlug):
    """    上传文档到工作区的文档库    """
    url = f"{BASE_URL}/document/upload"
    headers = {"accept": "application/json",
               "Authorization": API_KEY,
               # "Content-Type": "multipart/form-data"
               }
    # with open(file_path, 'rb') as frb:
    # file_rb = open(file_path, 'rb')
    files = {'file': open(file_path, 'rb')}
    data = {"workspaceSlug": workspaceSlug}

    response = requests.post(url, headers=headers, files=files, data=data)
    # print(response.text)
    upload_result = response.json().get('success')
    location = response.json().get('documents')[0]['location']
    print(f"upload_result: {upload_result}\nlocation: {location}")
    return upload_result, location

    # 上传失败：
    # {"success":false,"error":"Invalid file upload. Multipart: Boundary not found"}
    # 上传成功：
    # {"success":true,"error":null,"documents":[
    # {"id":"238aeefb-4eaa-46fd-a09a-ae721d1ff0b4",
    # "url":"file://C:\\Users\\lihz\\AppData\\Roaming\\xxx.txt",
    # "title":"xxx.txt","docAuthor":"Unknown","description":"Unknown",
    # "docSource":"a text file uploaded by the user.","chunkSource":"",
    # "published":"2025/2/18 10:02:27","wordCount":1,
    # "pageContent":"月光下的诺言\n初夏的傍晚，...这样的时光，才是真正属于她的。\n\n",
    # "token_count_estimate":2089,
    # "location":"custom-documents/aeaaceoe.txt-238aeefb-4eaa-46fd-a09a-ae721d1ff0b4.json"}]}


def move_file_to_workspace(workspaceSlug, file_locations_list):
    url = f"{BASE_URL}/workspace/{workspaceSlug}/update-embeddings"
    headers = {
        "accept": "application/json",
        "Authorization": API_KEY,
        "Content-Type": "application/json"
    }
    data = {"adds": file_locations_list,
            "deletes": ["custom-documents/anythingllm.txt-hash.json"]
            }

    response = requests.post(url, headers=headers, json=data)
    print(response.text)

    # 执行成功：
    # {"workspace":{"id":20,"name":"18日10:55:46","slug":"18105546","vectorTag":null,
    # "createdAt":"2025-02-18T02:55:48.675Z","openAiTemp":0.7,"openAiHistory":20,
    # "lastUpdatedAt":"2025-02-18T02:55:48.675Z","openAiPrompt":"Custom prompt for responses",
    # "similarityThreshold":0.7,"chatProvider":null,"chatModel":null,"topN":4,"chatMode":"query",
    # "pfpFilename":null,"agentProvider":null,"agentModel":null,"queryRefusalResponse":"Custom refusal message",
    # "vectorSearchMode":"default","documents":[
    #
    # {"id":5,"docId":"abe44edb-2bfc-4e90-b3d2-069a6f434e90",
    # "filename":"test1.docx-76e26ce6-033a-4bfb-9ef2-e89c3a15479f.json",
    # "docpath":"custom-documents/test1.docx-76e26ce6-033a-4bfb-9ef2-e89c3a15479f.json",
    # "workspaceId":20,"metadata":"{\"id\":\"76e26ce6-033a-4bfb-9ef2-e89c3a15479f\",
    # \"url\":\"xxxt1.docx\",\"title\":\"test1.docx\",\"docAuthor\":\"no author found\",
    # \"description\":\"No description found.\",\"docSource\":\"pdf file uploaded by the user.\",
    # \"chunkSource\":\"\",\"published\":\"2025/2/18 10:55:50\",\"wordCount\":53,\"token_count_estimate\":166}",
    # "pinned":false,"watched":false,"createdAt":"2025-02-18T02:56:02.103Z","lastUpdatedAt":"2025-02-18T02:56:02.103Z"},
    #
    # {"id":6,"docId":"dcc64fe1-65c8-475a-8a84-6b15741b28b4",
    # "filename":"test-eae-aJSONaaaaajson-aae.docx-644afa6a-02bf-472a-b77c-9d3e8b40c895.json",
    # "docpath":"custom-documents/test-eae-aJSONaaaaajson-aae.docx-644afa6a-02bf-472a-b77c-9d3e8b40c895.json",
    # "workspaceId":20,"metadata":"{\"id\":\"644afa6a-02bf-472a-b77c-9d3e8b40c895\",
    # \"url\":xxx.docx\",\"title\":\xxx.docx\",\"docAuthor\":\"no author found\",
    # \"description\":\"No description found.\",\"docSource\":\"pdf file uploaded by the user.\",
    # \"chunkSource\":\"\",\"published\":\"2025/2/18 10:55:53\",\"wordCount\":53,\"token_count_estimate\":166}",
    # "pinned":false,"watched":false,"createdAt":"2025-02-18T02:56:02.652Z","lastUpdatedAt":"2025-02-18T02:56:02.652Z"},
    #
    # {"id":7,"docId":"b69ddd88-9061-4814-a688-548dd9abb98d",
    # "filename":"eaee(r)ecent.txt-db8de62c-3f00-407e-bfd0-fd41e0d59019.json",
    # "docpath":"custom-documents/eaee(r)ecent.txt-db8de62c-3f00-407e-bfd0-fd41e0d59019.json",
    # "workspaceId":20,"metadata":"{\"id\":\"db8de62c-3f00-407e-bfd0-fd41e0d59019\",
    # \"url\":\"xxx.txt\",\"title\":xxx.txt\",\"docAuthor\":\"Unknown\",
    # \"description\":\"Unknown\",\"docSource\":\"a text file uploaded by the user.\",
    # \"chunkSource\":\"\",\"published\":\"2025/2/18 10:55:56\",\"wordCount\":1,\"token_count_estimate\":119}",
    # "pinned":false,"watched":false,"createdAt":"2025-02-18T02:56:03.186Z","lastUpdatedAt":"2025-02-18T02:56:03.186Z"},
    #
    # {"id":8,"docId":"a3171443-ca51-472e-9685-4a25217556e3",
    # "filename":"aeaaceoe.txt-6e8c3f4a-ca6b-47fa-a9f2-55b92e27e892.json",
    # "docpath":"custom-documents/aeaaceoe.txt-6e8c3f4a-ca6b-47fa-a9f2-55b92e27e892.json",
    # "workspaceId":20,"metadata":"{\"id\":\"6e8c3f4a-ca6b-47fa-a9f2-55b92e27e892\",
    # \"url\":\xxx.txt\",\"title\":\"xxx.txt\",\"docAuthor\":\"Unknown\",
    # \"description\":\"Unknown\",\"docSource\":\"a text file uploaded by the user.\",
    # \"chunkSource\":\"\",\"published\":\"2025/2/18 10:55:58\",\"wordCount\":1,\"token_count_estimate\":2089}",
    # "pinned":false,"watched":false,"createdAt":"2025-02-18T02:56:04.345Z","lastUpdatedAt":"2025-02-18T02:56:04.345Z"}]}}

# 上传文件到工作区
# def add_file_to_workspace(workspace_slug, file_path):
#     url = f"{BASE_URL}/workspace/{workspace_slug}/update-embeddings"
#     with open(file_path, "rb") as file:
#         files = {
#             "file": file
#         }
#         response = requests.post(url, files=files)
#     if response.status_code == 201:
#         print("文件上传成功")
#     else:
#         print(f"文件上传失败，状态码: {response.status_code}, 响应: {response.text}")


# 发送问题并获取答案
def ask_question(workspaceSlug, question):
    url = f"{BASE_URL}/workspaces/{workspaceSlug}/chat"
    headers = {
        "Content-Type": "application/json"
    }
    data = {
        "question": question
    }
    response = requests.post(url, headers=headers, json=data)
    if response.status_code == 200:
        answer = response.json().get("answer")
        print(f"问题: {question}")
        print(f"答案: {answer}")
    else:
        print(f"提问失败，状态码: {response.status_code}, 响应: {response.text}")


if __name__ == "__main__":
    # 新建工作区
    # filepath = 'F:\\a_Coding\\b_IT_Books\\it_books_learning\\08_webServer\\k_khlc2025\\月光下的诺言.txt'
    files_list = ['E:\\lihz\\10-Library\\08_webServer\\k_khlc2025\\test-表格、JSON、公式、坏json - 副本.docx',
                  # 'E:\\lihz\\10-Library\\08_webServer\\k_khlc2025\\test1.docx',
                  # 'E:\\lihz\\10-Library\\08_webServer\\k_khlc2025\\过河问题.txt',
                  # 'E:\\lihz\\10-Library\\08_webServer\\k_khlc2025\\月光下的诺言.txt'
                  ]
    WorkspaceName = getFtime()
    workspaceSlug = create_workspace(WorkspaceName)
    file_locations_list = []
    for filepath in files_list:
        upload_result, location = upload_file(filepath, workspaceSlug)
        if upload_result:
            file_locations_list.append(location)
    move_file_to_workspace(workspaceSlug, file_locations_list)

